package org.example.wx.config;

import io.minio.MinioClient;
import io.minio.ListBucketsArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class MinioHealthCheck {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.access-key:admin}")
    private String accessKey;

    @Value("${minio.secret-key:admin123}")
    private String secretKey;

    /**
     * 应用启动后检查MinIO连接
     */
    @PostConstruct
    public void checkMinioConnection() {
        log.info("开始检查MinIO连接状态...");
        
        // 尝试不同的端口和配置
        List<String> endpoints = Arrays.asList(
            "http://39.96.219.197:9000",
            "http://39.96.219.197:9001", 
            "http://39.96.219.197:9002",
            "http://39.96.219.197:8080",
            "http://39.96.219.197:8090"
        );
        
        for (String endpoint : endpoints) {
            try {
                MinioClient testClient = MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
                
                // 测试连接
                testClient.listBuckets(ListBucketsArgs.builder().build());
                log.info("✅ MinIO连接成功！正确的端点是: {}", endpoint);
                log.info("请将此端点更新到application.yml配置文件中");
                return;
                
            } catch (Exception e) {
                log.debug("端点 {} 连接失败: {}", endpoint, e.getMessage());
            }
        }
        
        log.error("❌ 所有MinIO端点都连接失败，请检查以下项目：");
        log.error("1. MinIO服务是否正在运行");
        log.error("2. 网络连接是否正常");
        log.error("3. 防火墙是否阻止了连接");
        log.error("4. 访问凭据是否正确 (当前: {}/***))", accessKey);
        log.error("5. 服务器地址是否正确: 39.96.219.197");
        
        // 提供诊断命令
        log.info("💡 诊断建议：");
        log.info("1. 手动测试连接: curl -v http://39.96.219.197:9000");
        log.info("2. 检查MinIO服务状态");
        log.info("3. 验证网络连接: ping 39.96.219.197");
        log.info("4. 检查防火墙设置");
    }
    
    /**
     * 运行时检查MinIO连接状态
     */
    public boolean isMinioAvailable() {
        try {
            minioClient.listBuckets(ListBucketsArgs.builder().build());
            return true;
        } catch (Exception e) {
            log.warn("MinIO当前不可用: {}", e.getMessage());
            return false;
        }
    }
}
